﻿using System;
using System.Data;
using System.Collections.Generic;

using HsTec.Mobile.Green.Model;
using HsTec.Mobile.Green.SqlServerDAL;
using HsTec.Mobile.Green.Util;

namespace HsTec.Mobile.Green.BLL
{
    /// <summary>
    /// 业务逻辑类ChangeRate 的摘要说明。
    /// </summary>
    public class ChangeRateBLL
    {
        private readonly HsTec.Mobile.Green.DAL.ChangeRateDAL dal = new HsTec.Mobile.Green.DAL.ChangeRateDAL();
        public ChangeRateBLL()
        { }
        #region  成员方法
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(string CR_IDs)
        {
            return dal.Exists(CR_IDs);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(HsTec.Mobile.Green.Model.ChangeRate model)
        {
            return dal.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public int Update(HsTec.Mobile.Green.Model.ChangeRate model)
        {
            return dal.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public int Delete(string CR_IDs)
        {
            return dal.Delete(CR_IDs);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public HsTec.Mobile.Green.Model.ChangeRate GetModel(int CR_ID)
        {

            return dal.GetModel(CR_ID);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataView GetList(string strWhere)
        {
            return dal.GetList(strWhere);
        }
        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataView GetList(int Top, string strWhere, string filedOrder)
        {
            return dal.GetList(Top, strWhere, filedOrder);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<HsTec.Mobile.Green.Model.ChangeRate> GetModelList(string strWhere)
        {
            DataView ds = dal.GetList(strWhere);
            return DataTableToList(ds.Table);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<HsTec.Mobile.Green.Model.ChangeRate> DataTableToList(DataTable dt)
        {
            List<HsTec.Mobile.Green.Model.ChangeRate> modelList = new List<HsTec.Mobile.Green.Model.ChangeRate>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                HsTec.Mobile.Green.Model.ChangeRate model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new HsTec.Mobile.Green.Model.ChangeRate();
                    if (dt.Rows[n]["CR_ID"].ToString() != "")
                    {
                        model.CR_ID = int.Parse(dt.Rows[n]["CR_ID"].ToString());
                    }
                    model.Years = dt.Rows[n]["Years"].ToString();
                    if (dt.Rows[n]["Powers"].ToString() != "")
                    {
                        model.Powers = decimal.Parse(dt.Rows[n]["Powers"].ToString());
                    }
                    if (dt.Rows[n]["TelecomRate"].ToString() != "")
                    {
                        model.TelecomRate = decimal.Parse(dt.Rows[n]["TelecomRate"].ToString());
                    }
                    if (dt.Rows[n]["BaseRate"].ToString() != "")
                    {
                        model.BaseRate = decimal.Parse(dt.Rows[n]["BaseRate"].ToString());
                    }
                    if (dt.Rows[n]["BusinessRate"].ToString() != "")
                    {
                        model.BusinessRate = decimal.Parse(dt.Rows[n]["BusinessRate"].ToString());
                    }
                    if (dt.Rows[n]["fTelecomRate"].ToString() != "")
                    {
                        model.fTelecomRate = decimal.Parse(dt.Rows[n]["fTelecomRate"].ToString());
                    }
                    if (dt.Rows[n]["fBaseRate"].ToString() != "")
                    {
                        model.fBaseRate = decimal.Parse(dt.Rows[n]["fBaseRate"].ToString());
                    }
                    if (dt.Rows[n]["fBusinessRate"].ToString() != "")
                    {
                        model.fBusinessRate = decimal.Parse(dt.Rows[n]["fBusinessRate"].ToString());
                    }
                    model.Type = dt.Rows[n]["Type"].ToString();
                    if (dt.Rows[n]["OperatUser"].ToString() != "")
                    {
                        model.OperatUser = DateTime.Parse(dt.Rows[n]["OperatUser"].ToString());
                    }
                    if (dt.Rows[n]["OperatDate"].ToString() != "")
                    {
                        model.OperatDate = DateTime.Parse(dt.Rows[n]["OperatDate"].ToString());
                    }
                    modelList.Add(model);
                }
            }
            return modelList;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataView GetAllList()
        {
            return GetList("");
        }

        #endregion  成员方法

        /// <summary>
        /// 三目标导向过程
        /// </summary>
        /// <param name="sTelecomRate">单位电信业务总量综合能耗下降率</param>
        /// <param name="sPowerRate">单载频基站耗电下降率</param>
        /// <param name="sBusinessRate">单位业务量能耗变化率</param>
        /// <param name="sYear">年份</param>
        /// <param name="dicRlt">返回计算数据</param>
        public string GoalOrientedProcess(string sTelecomRate, string sPowerRate, string sBusinessRate, string sYear, Dictionary<string, string> dicRlt)
        {
            #region  准备工作 完成基本数据的提出工作

            //获取转换率
            EnergyCalc ec = new EnergyCalc();
            string DiscountRate = String.Empty;
            dicRlt.Add("Err", String.Empty);
            //预测业务量
            string sTrafficForecas = String.Empty;
            //载频数
            string sSetFrequency = String.Empty;
            //基站耗电占比
            string sConsumptionAccounting = String.Empty;
            //电信业务量
            string sTelecommunicationTraffic = String.Empty;
            //电能占综合能耗占比
            string sEnergyAccounting = String.Empty;

            //0.获取本年度计算所需的参数
            DataView tmp = SQLHelper.ExecuteDataView("select * from tb_GoalOriente where Years = '" + sYear + "' and Type='2'");
            if (tmp.Count == 0)
            {
                return sYear + "年度的预测业务量、载频数、基站耗电占比、电信业务量、电能占综合能耗占比未录入！";
            }
            else
            {
                sTrafficForecas = tmp[0]["TrafficForecast"].ToString();
                sSetFrequency = tmp[0]["SetFrequency"].ToString();
                sConsumptionAccounting = tmp[0]["ConsumptionAccounting"].ToString();
                sTelecommunicationTraffic = tmp[0]["TelecommunicationTraffic"].ToString();
                sEnergyAccounting = tmp[0]["EnergyAccounting"].ToString();
            }

            #endregion

            #region 计算三目标导向过程

            //获取上一年的 
            //1.计算预测耗电量
            //1.1 单位电信业务总量综合能耗下降率
            //获取单位电信业务总量  取耗电量  取业务总量   如果年份是2009年
            //---------------------------------------------------------------------需要改进 如何从动态表中获取信息-----------
            DateTime dLastYears = DateTime.Parse(sYear + "-01-01").AddYears(-1);
            string sPower = SQLHelper.ExecuteString("select sum(Power) from rt_EnergyConsumption where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string sGasoline = SQLHelper.ExecuteString("select sum(Gasoline) from rt_EnergyConsumption where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string sDieselFuel = SQLHelper.ExecuteString("select sum(DieselFuel) from rt_EnergyConsumption where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string sBusiness = SQLHelper.ExecuteString("select sum(Value) from rt_Traffic where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            if (String.IsNullOrEmpty(sPower))
            {
                return dLastYears.ToString("yyyy") + "年耗电量为空，请录入相关数据！";
            }
            if (String.IsNullOrEmpty(sBusiness))
            {
                return dLastYears.ToString("yyyy") + "年电信业务量为空，请导入相关数据！";
            }
            sGasoline = String.IsNullOrEmpty(sGasoline) ? "0" : sGasoline;
            sDieselFuel = String.IsNullOrEmpty(sDieselFuel) ? "0" : sDieselFuel;
            if (String.IsNullOrEmpty(sDieselFuel))
            {
                return dLastYears.ToString("yyyy") + "年电信业务量为空，请导入相关数据！";
            }
            //---------------------------------------------------------------------------------------------------------------
            double dBusinessTotal = (double.Parse(sPower) * 0.1229 + double.Parse(sGasoline) * 1.4714 * 0.72 + double.Parse(sDieselFuel) * 1.4571 * 0.83) / double.Parse(sBusiness);
            string sBusinessTotal = (dBusinessTotal * 10000).ToString("0.00");
            double dComprehensiveEnergy = double.Parse(sBusinessTotal) * (1 - double.Parse(sTelecomRate)) * double.Parse(sTelecommunicationTraffic);
            double dPower1 = dComprehensiveEnergy * double.Parse(sEnergyAccounting) / 0.1229;
            dicRlt.Add("ForecastConsumption1", sTelecomRate + "," + sTelecommunicationTraffic + "," + dComprehensiveEnergy.ToString("0.00") + "," + sEnergyAccounting + "," + dPower1.ToString("0.00"));
            dicRlt.Add("dPower1", dPower1.ToString());
            //1.2 单载频基站耗电下降率
            //---------------------------------------------------------------------需要改进 如何从动态表中获取信息-----------
            //耗电值到底取那个 是总耗电 还是基站耗电
            //string sRateBase = SQLHelper.ExecuteString("select top 1 Proportion/100 from tb_EnergyProportion where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and  Subentry='Powers_3_1' and Area_ID='-1'");
            //string sRateP3 = SQLHelper.ExecuteString("select top 1 Proportion/100 from tb_EnergyProportion where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and  Subentry='Powers_3' and Area_ID='-1'");
            //if (String.IsNullOrEmpty(sRateBase))
            //{
            //    return sYear + "年省公司能耗比例未设置无法获取基站计算比例，请输入相关数据！";
            //}
            //string sBasePower = SQLHelper.ExecuteString("select sum(Power)*" + sRateBase + "*" + sRateP3 + " from rt_EnergyConsumption where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string sBasePower = SQLHelper.ExecuteString("select sum(Powers_3_1) from tb_ReportAnalysis where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string s2GFrequency = SQLHelper.ExecuteString("select avg(Value) from rt_2Gcf where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string s3GFrequency = SQLHelper.ExecuteString("select avg(Value) from rt_3Gcf where SUBSTRING(Years,1,4)='" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            if (String.IsNullOrEmpty(sBasePower))
            {
                return dLastYears.ToString("yyyy") + "年基站耗电量为空，请录入相关数据！";
            }
            if (String.IsNullOrEmpty(s2GFrequency))
            {
                return dLastYears.ToString("yyyy") + "年2G载频到达数为空，请导入相关数据！";
            }
            if (String.IsNullOrEmpty(s2GFrequency))
            {
                return dLastYears.ToString("yyyy") + "年2G载频到达数为空，请导入相关数据！";
            }
            if (String.IsNullOrEmpty(s3GFrequency))
            {
                return dLastYears.ToString("yyyy") + "年3G载频到达数为空，请导入相关数据！";
            }
            //---------------------------------------------------------------------------------------------------------------
            double dFrequencyTotal = double.Parse(sBasePower) / (double.Parse(s2GFrequency) + double.Parse(s3GFrequency));
            double dBasePower = dFrequencyTotal * (1 - double.Parse(sPowerRate)) * double.Parse(sSetFrequency);
            double dPower2 = dBasePower / double.Parse(sConsumptionAccounting);
            dicRlt.Add("ForecastConsumption2", sPowerRate + "," + sSetFrequency + "," + dBasePower.ToString() + "," + sConsumptionAccounting + "," + dPower2.ToString());
            dicRlt.Add("dPower2", dPower2.ToString());
            //1.3 单位业务量能耗变化率
            //---------------------------------------------------------------------需要改进 如何从动态表中获取信息-----------
            string s2gFlow = SQLHelper.ExecuteString("select sum(Value) from rt_2GFlow where  SUBSTRING(Years,1,4) = '" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string s3gFlow = SQLHelper.ExecuteString("select sum(Value) from rt_3GFlow where  SUBSTRING(Years,1,4) = '" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string sPhone = SQLHelper.ExecuteString("select sum(Value*5.85) from rt_Telephone where  SUBSTRING(Years,1,4) = '" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            string sTD = SQLHelper.ExecuteString("select sum(Value*5.49) from rt_TDTraffic where  SUBSTRING(Years,1,4) = '" + dLastYears.ToString("yyyy") + "' and Area_ID='41'");
            double dTrafficLastYears = Double.Parse(String.IsNullOrEmpty(s2gFlow) ? "0" : s2gFlow) +
                            Double.Parse(String.IsNullOrEmpty(s3gFlow) ? "0" : s3gFlow) +
                            Double.Parse(String.IsNullOrEmpty(sPhone) ? "0" : sPhone) +
                            Double.Parse(String.IsNullOrEmpty(sTD) ? "0" : sTD);
            //---------------------------------------------------------------------------------------------------------------
            double dBusinessPowerTotal = double.Parse(sPower) / dTrafficLastYears;
            double dPower3 = dBusinessPowerTotal * (1 - double.Parse(sBusinessRate)) * double.Parse(sTrafficForecas) * 10000;
            dicRlt.Add("ForecastConsumption3", sBusinessRate + "," + sTrafficForecas + "," + dPower3.ToString());
            dicRlt.Add("dPower3", dPower3.ToString());
            //1.4 计算最小耗电值
            double dMinPower = dPower1 < dPower2 ? (dPower1 < dPower3 ? dPower1 : dPower3) : (dPower2 < dPower3 ? dPower2 : dPower3);
            dicRlt.Add("MinPower", dMinPower.ToString());
            double dTPowerRate = 0;
            double dTsBusinessRate = 0;
            double dTTelecomRate = 0;
            //2.计算三个下降率
            if (dMinPower == dPower1)
            {
                dTTelecomRate = double.Parse(sTelecomRate);
                // 如何按单位电信业务总量综合能耗下降率
                double dMinBasePower = dMinPower * double.Parse(sConsumptionAccounting);
                double dStationPower = dMinBasePower / double.Parse(sSetFrequency);
                //得到每载频基站变化率
                dTPowerRate = -((dStationPower / dFrequencyTotal) - 1);    //---------
                double dBusiness = dMinPower / double.Parse(sTrafficForecas) ;
                dTsBusinessRate = -((dBusiness / (dBusinessPowerTotal * 10000)) - 1); //--------
            }
            else if (dMinPower == dPower2)
            {
                dTPowerRate = double.Parse(sPowerRate);
                // 如何按单载频基站耗电下降率
                double dTComprehensiveEnergy = dMinPower * 0.1229 / double.Parse(sEnergyAccounting);  //综合能耗
                double dTTelecom = dTComprehensiveEnergy / double.Parse(sTelecommunicationTraffic);
                dTTelecomRate = -((dTTelecom / double.Parse(sBusinessTotal)) - 1);      //--------
                double dBusiness = dMinPower / double.Parse(sTrafficForecas) ;
                dTsBusinessRate = -((dBusiness / dBusinessPowerTotal * 10000) - 1); //--------
            }
            else
            {
                dTsBusinessRate = double.Parse(sBusinessRate);
                // 如何按单位业务量能耗变化率
                // 如何按单位电信业务总量综合能耗下降率
                double dMinBasePower = dMinPower * double.Parse(sConsumptionAccounting);
                double dStationPower = dMinBasePower / double.Parse(sSetFrequency);
                //得到每载频基站变化率
                dTPowerRate = -((dStationPower / dFrequencyTotal) - 1);    //---------
                double dTComprehensiveEnergy = dMinPower * 0.1229 / double.Parse(sEnergyAccounting);  //综合能耗  //sConsumptionAccounting
                double dTTelecom = dTComprehensiveEnergy / double.Parse(sTelecommunicationTraffic);
                dTTelecomRate = -((dTTelecom / double.Parse(sBusinessTotal)) - 1);      //--------
            }
            dicRlt.Add("TelecomRate", dTTelecomRate.ToString());
            dicRlt.Add("BaseRate", dTPowerRate.ToString());
            dicRlt.Add("BusinessRate", dTsBusinessRate.ToString());
            return null;
            #endregion
        }
    }
}

